package com.lzx.iteam;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.SalaryFieldEditAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.SalaryFieldBean;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.WithoutObjMsg;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.MyListView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2017年 01月 10日
 * Time: 下午3:17
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 设置自定义字段页面
 */
public class SalaryFieldEditActivity extends MyBaseActivity {


    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.listview_only)
    private ListView mListView;

    private ArrayList<SalaryFieldBean> mDatas;
    private SalaryFieldEditAdapter mAdapter;

    private String mGroupId;

    private final int SET_SALARY_FIELDS = 30001;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            waitDlgDismiss();
            if (msg.arg1 == 0){
                switch (msg.what){
                    case SET_SALARY_FIELDS:
                        showShortToast("设置成功");
                        Intent intent = new Intent();
                        mDatas.add(0,new SalaryFieldBean("基本工资"));
                        intent.putExtra("salary_rule",mDatas);
                        setResult(RESULT_OK,intent);
                        finish();
                        break;

                }
            }else{
                Toast.makeText(mActivity, (String) msg.obj,
                      Toast.LENGTH_LONG).show();
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState,R.layout.only_list_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mTvTitle.setText("编辑字段");
        mTvRight.setText("保存");

        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mDatas = (ArrayList<SalaryFieldBean>) intent.getSerializableExtra("salary_field");

        if (mDatas == null) {
            mDatas = new ArrayList<>();
            mDatas.add(new SalaryFieldBean("岗位津贴"));
            mDatas.add(new SalaryFieldBean("奖金"));
        }else{
            mDatas.remove(0);
        }

        View footerView = LayoutInflater.from(this).inflate(R.layout.salary_footer_layout,null);
        LinearLayout addView = (LinearLayout) footerView.findViewById(R.id.ll_salary_field_add);

        mListView.addFooterView(footerView);
        mAdapter = new SalaryFieldEditAdapter(this,mDatas);
        mListView.setAdapter(mAdapter);
        addView.setOnClickListener(this);

    }

    public void addField(){

        if (mDatas.size() >= 6){
            showShortToast("");
        }else{
            getFieldData(false);
            mDatas.add(new SalaryFieldBean(""));
            mAdapter.notifyDataSetChanged();
        }

    }

    public void deleteField(int posotion){
        getFieldData(false);
        mDatas.remove(posotion);
        mAdapter.notifyDataSetChanged();
    }

    /**
     *
     * @param flag
     */
    private void getFieldData(boolean flag){
        mDatas.clear();
        for (int i = 0; i < mListView.getChildCount() - 1; i++) {
            LinearLayout layout = (LinearLayout) mListView.getChildAt(i);// 获得子item的layout
            EditText et = (EditText) layout.getChildAt(0).findViewById(R.id.vote_item_et_content);// 从layout中获得控件,根据其id
            // EditText et = (EditText) layout.getChildAt(1)//或者根据位置,在这我假设TextView在前，EditText在后
            String s = et.getText().toString().trim();
            if (StringUtil.isEmpty(s)){
                s = "";
            }
            if (flag){
                if (!StringUtil.isEmpty(s)){
                    mDatas.add(new SalaryFieldBean(s));
                }
            }else{
                mDatas.add(new SalaryFieldBean(s));
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_ll_back:
                finish();
                break;
            case R.id.title_tv_right:
                getFieldData(true);
                JSONArray array = new JSONArray();
                try {
                    for (int i = 0; i < mDatas.size(); i++) {
                        JSONObject object = new JSONObject();
                        object.put("order", i + 1);
                        object.put("name", mDatas.get(i).getName());
                        array.put(object);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                waitDlgShow();
                setSalaryFields(array.toString());
                break;
            case R.id.ll_salary_field_add:
                addField();
                break;
        }
    }

    /**
     * 设置工资扣税
     */
    private void setSalaryFields(String fields){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SALARY_FIELDS,fields));
        WithoutObjMsg msg = new WithoutObjMsg(mHandler.obtainMessage(SET_SALARY_FIELDS));
        msg.mApi = AsynHttpClient.API_SALARY_SET_SALARY_FIELDS;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
    }

}
